//
//  LogSystem.m
//  AutoCompilerManager
//
//  Created by Vescky on 13-9-5.
//  Copyright (c) 2013年 Vescky. All rights reserved.
//

#import "LogSystem.h"
#import "DateUtility.h"
#import "ReadConfig.h"

@implementation LogSystem

LogSystem *lSystem;

+ (id)shareLogSystem {
    if (!lSystem) {
        lSystem = [[LogSystem alloc] init];
    }
    return lSystem;
}

- (void)recordLogs {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *dateStr = getStringFromDate(@"yyyy_MM_dd", [NSDate date]);
    NSString *logPath = [NSString stringWithFormat:@"%@/%@.log",[ReadConfig readConfigByKey:@"SERVER_SYS_LOG_PATH"],dateStr];
    if (![fm fileExistsAtPath:logPath]) {
        fclose(stderr);
        fclose(stdout);
        //关闭前面的流
    }
    [self redirectNSLogToLogPath:logPath];
}

- (void)redirectNSLogToLogPath:(NSString*)logPath {
    freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
    freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stdout);
}

- (void)saveRecord:(id)record forKey:(NSString*)key {
    if (!record || !key) {
        return;
    }
    
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *dateStr = getStringFromDate(@"yyyy_MM", [NSDate date]);
    NSString *plistPath = [NSString stringWithFormat:@"%@/%@.plist",[ReadConfig readConfigByKey:@"SERVER_SYS_LOG_PATH"],dateStr];
    if (![fm fileExistsAtPath:plistPath]) {
        NSString *emptyPllistContent = [[NSBundle mainBundle] pathForResource:@"empty" ofType:@"plist"];
        NSData *emptyData = [[NSData alloc] initWithContentsOfFile:emptyPllistContent];
        [fm createFileAtPath:plistPath contents:emptyData attributes:nil];
    }
    NSMutableDictionary *idList = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    
    //处理重复key
    NSString *tmpKey = [key copy];
    int i = 1;
    while ([idList objectForKey:tmpKey]) {
        tmpKey = [NSString stringWithFormat:@"%@-%d",key,i++];
    }
    
    key = tmpKey;
    
    [idList setObject:record forKey:key];
    [idList writeToFile:plistPath atomically:YES];
}

@end
